<?php
class Upload extends Controller {
	private $config;
	private $app;
	public function html() {
		$this->config = include SERVER_PATH.'/config/upload.php';
		
		$this->app = $this->get('app', 'str');
		if(!isset($this->config[$this->app])) $this->displayJSON(array('status' => -1, 'message' => '未知应用'));
		
		$this->{$this->config[$this->app]['method']}();
	}
	private function productImage() {
		$this->app = 'productImage';
		if($this->config[$this->app]['auth']) {
			//应用认证
			$hash = $this->get('hash', 'str');
			if(!$hash) $this->displayJSON(array('status' => -2, 'message' => '缺少认证hash值'));
			
			include SERVER_PATH.'/extend/upload.extend.php';
			$result = Upload_extend::auth($this->app, $this->config[$this->app]['secret'], $hash);
			if(!$result) $this->displayJSON(array('status' => -3, 'message' => '认证失败'));
		}
		//扩展名检查
		if(!isset($_FILES['Filedata'])) $this->displayJSON(array('status' => -4, 'message' => '无上传'));
		
		$extension = Image::extension($_FILES['Filedata']['tmp_name']);
		if(!$extension || !in_array($extension, $this->config[$this->app]['ext'])) $this->displayJSON(array('status' => -5, 'message' => '上传文件格式错误'));
		
		
		$path = 'images/'.date('Ymd', time()).'/original/';
		if(!is_dir($path)) {
			if(!FileSystem::mkdir($this->config[$this->app]['path'].$path)) $this->displayJSON(array('status' => -6, 'message' => '目录无写权限'));
		}
		$filename = date('YmdHis', time()).'_'.str_replace(' ', '-', $_FILES['Filedata']['name']);
		$destination = $this->config[$this->app]['path'] . $path . $filename;
		
		if(!move_uploaded_file($_FILES['Filedata']['tmp_name'], $destination)) {
			$this->displayJSON(array('status' => -7, 'message' => '移动上传文件错误'));
		} else {
			$this->displayJSON(array('status' => 0, 'message' => '上传成功', 'src' => 'http://data.yueshihui.com/'. $path . $filename, 'val' => $path . $filename));
		}
	}
}